<?php
namespace app\model;

//
//require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
//require_once get_path('plugin/lingze/core/model.php');;
class Koi{
//锦鲤

    /**
     * Desc:获取对应条件下的锦鲤数量
     * User: cbw
     * Time: 2021/1/5 6:32 下午
     * @param $themeid
     * @param string $title
     * @param int $in_prize
     * @return mixed
     */
    public static function getKoiListCount($themeid,$title='',$in_prize=0)
    {
        $condition = "";
        if (!empty($title)){
            $condition .= " and title='".$title."'";
        }
        if ($in_prize){
            switch ($in_prize){
                case 1:
                case 2:
                    $condition .= " and in_prize=$in_prize";
                    break;
                default:
                    break;
            }
        }
        $sql = " select count(*) as cnt from ".tablename(koi_list)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取对应条件的锦鲤列表
     * User: cbw
     * Time: 2021/1/5 6:37 下午
     * @param $themeid
     * @param string $title
     * @param int $in_prize
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getKoiList($themeid,$title='',$in_prize=0,$page_start=0,$page_size=0,$is_max=0)
    {
        $condition = "";
        if (!empty($title)){
            $condition .= " and title='".$title."'";
        }
        if ($in_prize){
            switch ($in_prize){
                case 1:
                case 2:
                    $condition .= " and in_prize=$in_prize";
                    break;
                default:
                    break;
            }
        }
        if ($is_max){
            $condition .= " and is_max=$is_max";
        }
        if ($page_start && $page_size){
            $condition .= " order by created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = " select * from ".tablename(koi_list)." where themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:插入锦鲤列表item
     * User: cbw
     * Time: 2021/1/5 6:41 下午
     * @param $data
     * @return false
     */
    public static function insertKoiItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_list,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    /**
     * Desc:更新锦鲤列表中的item的信息
     * User: cbw
     * Time: 2021/1/5 6:43 下午
     * @param $where
     * @param $data
     * @return bool
     */
    public static function editKoiItemByWhere($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(koi_list,$data,$where);
        if (!empty($res)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * Desc:通过锦鲤列表id或者对应的记录
     * User: cbw
     * Time: 2021/1/5 6:53 下午
     * @param $id
     * @return mixed
     */
    public static function getKoiItemById($id,$themeid)
    {
        $res = db_get(koi_list,['l_id'=>$id,'themeid'=>$themeid]);
        return $res;
    }

    /**
     * Desc:获取锦鲤记录 通过奖项名称
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/4/6 9:34 上午
     * @param $name
     * @return array
     */
    public static function getKoiItemByName($name,$themeid)
    {
        $res = [];
        if ($name){
            $res = db_get(koi_list,['title'=>$name,'themeid'=>$themeid]);
        }
        return $res;
    }

    /**
     * Desc:删除锦鲤记录
     * User: cbw
     * Time: 2021/1/6 11:08 上午
     * @param $id
     * @param $themeid
     * @return mixed
     */
    public static function delKoiItemById($id,$themeid)
    {
        $res = db_delete(koi_list,['l_id'=>$id,'themeid'=>$themeid]);
        return $res;
    }
//锦鲤攻略

    /**
     * Desc:获取锦鲤攻略列表数量
     * User: cbw
     * Time: 2021/1/5 6:50 下午
     * @param $themeid
     * @return mixed
     */
    public static function getKoiMethodCount($themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(koi_method)." where themeid=$themeid";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取锦鲤攻略列表
     * User: cbw
     * Time: 2021/1/5 7:04 下午
     * @param $themeid
     * @return mixed
     */
    public static function getKoiMethodList($themeid,$page_start=0,$page_size=0,$status=0)
    {
        $condition="";
        if ($status!=0){
            $condition .= " and status=$status";
        }
        if ($page_start && $page_size){
            $condition .= " order by created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = " select * from ".tablename(koi_method)." where themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:插入锦鲤攻略item
     * User: cbw
     * Time: 2021/1/5 7:06 下午
     * @param $data
     * @return false
     */
    public static function insertKoiMethodItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_method,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    /**
     * Desc:更新锦鲤攻略的item
     * User: cbw
     * Time: 2021/1/5 7:07 下午
     * @param $id
     * @param $data
     * @return mixed
     */
    public static function editKoiMethodItemById($id,$data)
    {
        $res = db_update(koi_method,$data,['m_id'=>$id]);
        return $res;
    }

    /**
     * Desc:获取锦鲤攻略的记录 通过id
     * User: cbw
     * Time: 2021/1/5 7:20 下午
     * @param $id
     * @return mixed
     */
    public static function getKoiMethodItemById($id,$themeid)
    {
        $res = db_get(koi_method,['m_id'=>$id,'themeid'=>$themeid]);
        return $res;
    }

    /**
     * Desc:检查用户是否存在可兑换霸王锦鲤的锦鲤组合 并修改插入
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/18 9:58 下午
     * @param $m_id
     * @param $themeid
     * @param $uid
     */
    public static function checkAndBindKing($m_id,$themeid,$uid)
    {
        $method_item = self::getKoiMethodItemById($m_id,$themeid);
        if ($method_item){
            $king_id = $method_item['compose'];
            $first_has = self::getKoiFlagItemByKoiId($themeid,$method_item['first'],$uid);
            $second_has = self::getKoiFlagItemByKoiId($themeid,$method_item['second'],$uid);
            $third_has = self::getKoiFlagItemByKoiId($themeid,$method_item['third'],$uid);
            $four_has = self::getKoiFlagItemByKoiId($themeid,$method_item['four'],$uid);
            $five_has = self::getKoiFlagItemByKoiId($themeid,$method_item['five'],$uid);

            if ($first_has && $second_has && $third_has && $four_has && $five_has){
                //插入霸王集成奖项记录
                $insert_data = [
                    'uid'=>$uid,
                    'from_type'=>'koi',
                    'from_type_id'=>$m_id,
                    'status'=>1,
                    'used'=>2,
                    'used_koi_id'=>$king_id,
                    'themeid'=>$themeid
                ];
                $insert_item = self::insertKoiFlagItem($insert_data);
                if ($insert_item){
                    $update_data = ['used'=>1];
                    $first_where = ['f_id'=>$first_has['f_id']];
                    $second_where = ['f_id'=>$second_has['f_id']];
                    $third_where = ['f_id'=>$third_has['f_id']];
                    $four_where = ['f_id'=>$four_has['f_id']];
                    $five_where = ['f_id'=>$five_has['f_id']];

                    $first_update = self::editKoiFlagItem($first_where,$update_data);
                    $second_update = self::editKoiFlagItem($second_where,$update_data);
                    $third_update = self::editKoiFlagItem($third_where,$update_data);
                    $four_update = self::editKoiFlagItem($four_where,$update_data);
                    $five_update = self::editKoiFlagItem($five_where,$update_data);
                }
            }
        }
    }
//奖项

    /**
     * Desc:获取对应类型的奖项的数量
     * User: cbw
     * Time: 2021/1/5 7:14 下午
     * @param $themeid
     * @param string $name
     * @param int $koi_id
     * @return mixed
     */
    public static function getKoiPrizeCount($themeid,$name='',$koi_id=0)
    {
        $condition = "";
        if (!empty($name)){
            $condition .= " and name='".$name."'";
        }
        if ($koi_id!=0){
            $condition .= " and koi_id=$koi_id ";
        }
        $sql = " select count(*) as cnt from ".tablename(koi_prize)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取对应条件的奖项列表 可分页
     * User: cbw
     * Time: 2021/1/5 7:18 下午
     * @param $themeid
     * @param string $name
     * @param int $koi_id
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getKoiPrizeList($themeid,$name='',$koi_id=0,$page_start=0,$page_size=0,$status=0)
    {
        $condition = "";
        if (!empty($name)){
            $condition .= " and name='".$name."'";
        }
        if ($koi_id!=0){
            $condition .= " and koi_id=$koi_id ";
        }
        if ($status!=0){
            $condition .= " and status=$status ";
        }
        if ($page_start && $page_size){
            $condition .= " order by created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = " select * from ".tablename(koi_prize)." where themeid=$themeid".$condition;
        return db_select($sql);
    }

    public static function getKoiPrizeTypeList($themeid)
    {
        $temp_arr = [];
        $list = self::getKoiPrizeList($themeid,'',0,0,0,1);
        $all = self::getNewKoiFlagCount($themeid,0,'default',0,0,0,0);
        if ($all){
            $all_arr = ['title'=>'全部','num'=>$all,'type_id'=>(int)0];
            array_push($temp_arr,$all_arr);
        }

        foreach ($list as $k =>$v){
            $item_count = self::getNewKoiFlagCount($themeid,0,'default',$v['p_id'],0,0,0);
            if ($item_count>0){
                $temp = ['title'=>mb_substr($v['name'],0,4,'utf-8'),'num'=>(int)$item_count,'type_id'=>(int)$v['p_id']];
                array_push($temp_arr,$temp);
            }
        }
        return $temp_arr;
    }

    /**
     * Desc:前端展示抽奖奖项用
     * User: cbw
     * Time: 2021/1/8 10:44 上午
     * @param $themeid
     * @param string $name
     * @param int $koi_id
     * @param int $page_start
     * @param int $page_size
     * @param int $status
     * @return mixed
     */
    public static function getKoiPrizeListJoinKoi($themeid,$name='',$is_lose=0,$status=0)
    {
        $condition = "";
        if (!empty($name)){
            $condition .= " and a.name='".$name."'";
        }
        if ($is_lose!=0){
            $condition .= " and a.is_lose=$is_lose ";
        }
        if ($status!=0){
            $condition .= " and a.status=$status ";
        }
        $condition .= " order by a.show_sort desc, a.pr asc ";

        $sql = "select a.p_id,a.name,a.short_name,a.qty,a.price,a.pr,a.show_sort,a.small_img,a.status,a.is_lose,b.l_id,b.title as l_title,b.img as l_img from ".tablename(koi_prize).
            " as a LEFT JOIN". tablename(koi_list)." as b on a.koi_id=b.l_id"." where a.themeid=$themeid  ".$condition;
        return db_select($sql);
    }

    /**
     * Desc:抽奖使用到的奖项的列表
     * User: cbw
     * Time: 2021/1/21 4:41 下午
     * @param $themeid
     * @param string $name
     * @param int $is_lose
     * @param int $status
     * @return mixed
     */
    public static function getKoiPriceListGetLt($themeid,$name='',$is_lose=0,$status=0)
    {
        $condition = "";
        if (!empty($name)){
            $condition .= " and a.name='".$name."'";
        }
        if ($is_lose!=0){
            $condition .= " and a.is_lose=$is_lose ";
        }
        if ($status!=0){
            $condition .= " and a.status=$status ";
        }
        $condition .= " and a.qty>0 order by  a.pr asc  ";

        $sql = "select a.p_id,a.name,a.short_name,a.qty,a.price,a.pr,a.show_sort,a.small_img,a.status,a.is_lose,b.l_id,b.title as l_title,b.img as l_img from ".tablename(koi_prize).
            " as a LEFT JOIN". tablename(koi_list)." as b on a.koi_id=b.l_id"." where a.themeid=$themeid ".$condition;
        return db_select($sql);
    }

    /**
     * Desc:获取中奖的总概率 通过p_ids
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/4/2 3:52 下午
     * @param $themeid
     * @param $ids
     * @return mixed
     */
    public static function getKoiPricePrsByIds($themeid,$ids)
    {
        $sql = " select sum(pr) as total_pr from ".tablename(koi_prize)." where themeid=$themeid and p_id in $ids";
        return db_find($sql);
    }

    public static function getPriceListGetLtByIds($themeid,$ids,$name='',$is_lose=0,$status=0)
    {
        $condition = "";
        if (!empty($name)){
            $condition .= " and a.name='".$name."'";
        }
        if ($is_lose!=0){
            $condition .= " and a.is_lose=$is_lose ";
        }
        if ($status!=0){
            $condition .= " and a.status=$status ";
        }
        $condition .= " and a.qty>0 and a.pr >0 and a.p_id in $ids order by a.pr asc ";

        $sql = "select a.p_id,a.name,a.short_name,a.qty,a.price,a.pr,a.show_sort,a.small_img,a.status,a.is_lose,b.l_id,b.title as l_title,b.img as l_img from ".tablename(koi_prize).
            " as a LEFT JOIN". tablename(koi_list)." as b on a.koi_id=b.l_id"." where a.themeid=$themeid ".$condition;
        return db_select($sql);
    }

    /**
     * Desc:插入奖项
     * User: cbw
     * Time: 2021/1/5 7:21 下午
     * @param $data
     * @return false
     */
    public static function insertKoiPrizeItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_prize,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    /**
     * Desc:更新奖项
     * User: cbw
     * Time: 2021/1/5 7:23 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editKoiPrizeItemByWhere($where,$data)
    {
        try {
            $res = db_update(koi_prize,$data,$where);
            return $res;
        }catch (Exception $e){
            var_dump($e->getMessage());die();
        }

    }

    /**
     * Desc:获取奖项记录 通过奖项id
     * User: cbw
     * Time: 2021/1/5 7:24 下午
     * @param $id
     * @return mixed
     */
    public static function getKoiPrizeItemById($themeid,$id)
    {
        $res = db_get(koi_prize,['p_id'=>$id]);
        return $res;
    }

    /**
     * Desc:获取奖项是否被使用
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/4/14 4:34 下午
     * @param $themeid
     * @param $p_id
     * @return mixed
     */
    public static function checkKoiPrizeUsed($themeid,$p_id)
    {
        $sql = " select count(*) as cnt from ".tablename(koi_flag)." where from_type='default' and from_type_id=$p_id and themeid=$themeid";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:删除
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/4/14 4:21 下午
     * @param $id
     * @return mixed
     */
    public static function delKoiPrizeItemById($themeid,$id)
    {
        return db_delete(koi_prize,['p_id'=>$id,'themeid'=>$themeid]);
    }


//抽奖机会

    /**
     * Desc:获取抽奖机会的记录数 对应条件
     * User: cbw
     * Time: 2021/1/5 7:33 下午
     * @param $themeid
     * @param int $uid
     * @param string $type
     * @return mixed
     */
    public static function getKoiChanceCount($themeid,$uid=0,$type='',$mark=0,$fromuid=0)
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and uid='{$uid}' ";
        }
        if ($fromuid!=0){
            $condition .= " and from_uid='{$fromuid}' ";
        }
        if (!empty($type)){
            $condition .= " and type='".$type."'";
        }
        if ($mark!=0){
            $condition .= " and mark=$mark ";
        }
        $sql = " select count(*) as cnt from ".tablename(koi_chance)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取抽奖机会的list 通过条件
     * User: cbw
     * Time: 2021/1/5 7:33 下午
     * @param $themeid
     * @param int $uid
     * @param string $type
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getKoiChanceList($themeid,$uid=0,$type='',$page_start=0,$page_size=0,$nickname='',$mobile='',$start_day='',$end_day='')
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and uid='{$uid}' ";
        }
        if (!empty($type)){
            $condition .= " and type='".$type."'";
        }
        if ($nickname){
            $condition .= "  and b.nickname like '".$nickname."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."' ";
        }
        if ($mobile){
            $condition .= "  and b.mobile='".$mobile."' ";
        }
        if ($page_start && $page_size){
            $condition .= " order by created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = "select a.*,b.username,b.avatar,b.nickname,b.mobile from ".tablename(koi_chance).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid where a.themeid=$themeid".$condition;

        return db_select($sql);
    }

    /**
     * Desc:插入抽奖记录
     * User: cbw
     * Time: 2021/1/5 7:34 下午
     * @param $data
     * @return false
     */
    public static function insertKoiChanceItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_chance,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    /**
     * Desc:更新抽奖记录
     * User: cbw
     * Time: 2021/1/5 7:34 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editKoiChanceItemByWhere($where,$data)
    {
        $res = db_update(koi_chance,$data,$where);
        return $res;
    }

    /**
     * Desc:获取用户的对应条件的抽奖记录
     * User: cbw
     * Time: 2021/1/5 7:35 下午
     * @param $where
     * @return mixed
     */
    public static function getKoiChanceItemByWhere($where)
    {
        $res = db_get(koi_chance,$where);
        return $res;
    }

    /**
     * Desc:获取幸运星的机会记录
     * User: cbw
     * Time: 2021/1/9 3:09 下午
     * @param $themeid
     * @param $uid
     * @param string $type
     * @param int $mark
     * @return mixed
     */
    public static function getUserluckyStarChanceItem($themeid,$uid,$from_uid,$type='lucky_star',$mark=2)
    {
        $res = db_get(koi_chance,['themeid'=>$themeid,'uid'=>$uid,'from_uid'=>$from_uid,'type'=>$type,'mark'=>$mark]);
        return $res;
    }
//中奖记录

    public static function getNewKoiFlagCount($themeid,$uid=0,$from_type='',$from_type_id=0,$status=0,$used_koi_id=0,$used=0)
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and uid='{$uid}' ";
        }
        if (!empty($from_type)){
            $condition .= " and from_type='".$from_type."'";
        }
        if (!empty($from_type_id)){
            $condition .= " and from_type_id=$from_type_id";
        }
        if ($used_koi_id){
            $condition .= " and used_koi_id=$used_koi_id";
        }
        if ($status!=0){
            $condition .= " and status=$status";
        }
        if ($used){
            $condition .= " and used=$used";
        }
        $sql = " select count(*) as cnt from ".tablename(koi_flag)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取中奖记录的数量
     * User: cbw
     * Time: 2021/1/6 9:00 上午
     * @param $themeid
     * @param int $uid
     * @param string $from_type
     * @param int $status
     * @return mixed
     */
    public static function getKoiFlagCount($themeid,$uid=0,$from_type='default',$from_type_id=0,$status=0,$used_koi_id=0,$used=0)
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and uid='{$uid}' ";
        }
        if (!empty($from_type)){
            $condition .= " and from_type='".$from_type."'";
        }
        if (!empty($from_type_id)){
            $condition .= " and from_type_id=$from_type_id";
        }
        if ($used_koi_id){
            $condition .= " and used_koi_id=$used_koi_id";
        }
        if ($status!=0){
            $condition .= " and status=$status";
        }
        if ($used){
            $condition .= " and used=$used";
        }
        $sql = " select count(*) as cnt from ".tablename(koi_flag)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取中奖记录的列表
     * User: cbw
     * Time: 2021/1/6 9:00 上午
     * @param $themeid
     * @param int $uid
     * @param string $from_type
     * @param int $status
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getKoiFlagList($themeid,$uid=0,$from_type='',$status=0,$page_start=0,$page_size=0,$nickname='',$mobile='',$start_day='',$end_day='')
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and a.uid='{$uid}' ";
        }
        if (!empty($from_type)){
            $condition .= " and a.from_type='".$from_type."'";
        }
        if ($status!=0){
            $condition .= " and a.status=$status";
        }
        if ($nickname){
            $condition .= "  and b.nickname like '".$nickname."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."' ";
        }
        if ($mobile){
            $condition .= "  and b.mobile='".$mobile."' ";
        }
        if ($page_start && $page_size){
            $condition .= " order by a.created_at desc limit ".$page_start.",".$page_size;
        }else{
            $condition .= " order by a.created_at desc ";
        }
        if (empty($from_type)){
            $sql = "select a.status,a.created_at,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.name,c.short_name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img,c.detail_imgs from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid".
                "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid".$condition;
            return db_select($sql);
        }elseif ($from_type=='default'){
            $sql = "select a.status,a.created_at,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.name,c.short_name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img,c.detail_imgs from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid".
                "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid".$condition;
            return db_select($sql);
        }elseif ($from_type=='koi'){
            $sql = "select a.status,a.created_at,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.title,c.img from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                " LEFT JOIN". tablename(koi_list). " as c on a.from_type_id=c.l_id where a.themeid=$themeid".$condition;
            return db_select($sql);
        }
    }

    /**
     * Desc:获取用户活动下的奖品数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/19 12:45 上午
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function apiGetPrizeCount($themeid,$uid)
    {
        $default_count = self::getNewKoiFlagCount($themeid,$uid,'default');
        $convert_count = self::getNewKoiFlagCount($themeid,$uid,'koi');
        return ['default_count'=>$default_count,'convert_count'=>$convert_count];
    }
    public static function getKoiUserFlagList($themeid,$type='',$status=0,$search='',$start_day='',$end_day='',$page_start=0,$page_size=0,$type_id=0,$uid=0,$workerid=0,$total=false)
    {
        $condition1 = " ";
        $condition = " ";

        if ($type){
            if ($type!='all' && $type!='-1'){
                $condition .= " and from_type='$type'";
            }
        }
        if ($type_id){
            $condition .= " and from_type_id=$type_id";
        }
        if ($uid){
            $condition .= " and a.uid='{$uid}'";
        }

        if ($workerid){
            $condition .= "  and b.workerid = '".$workerid."' ";
        }
        if ($status && $status!==-1){
            $condition .= " and a.status=$status";
        }
        if ($search){
            $condition .= " and b.nickname like '".$search."'"." or b.mobile like '".$search."' ";
        }
        if ($start_day && $end_day ){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($page_size && !$total){
            $condition1 = " limit ".$page_start.",".$page_size;
        }
        if ($type=='koi'){
            $sql = "select a.status,a.created_at,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.title,c.img from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                " LEFT JOIN". tablename(koi_list). " as c on a.from_type_id=c.l_id where a.themeid=$themeid".$condition."  order by a.created_at desc ".$condition1;

            return db_select($sql);
        }else{
            if ($total){
                $sql = "select count(*) from ".tablename(koi_flag).
                    " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid".
                    "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid".$condition."  order by a.created_at desc ".$condition1;
                return (int)db_fetchcolumn($sql);
            }else{
                $sql = "select a.status,a.created_at,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img from ".tablename(koi_flag).
                    " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid".
                    "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid".$condition."  order by a.created_at desc ".$condition1;
                return db_select($sql);
            }
        }
    }

    public static function getKoiTypeList($themeid)
    {
        return [
            ['title'=>'全部','num'=>self::getNewKoiFlagCount($themeid),'type'=>'all'],
            ['title'=>'奖品','num'=>self::getNewKoiFlagCount($themeid,0,'default'),'type'=>'default'],
            ['title'=>'合成锦鲤','num'=>self::getNewKoiFlagCount($themeid,0,'koi'),'type'=>'koi'],
        ];
    }

    public static function getKoiFlagTypeList($themeid,$type='')
    {
        return [
            ['title'=>'全部','num'=>self::getKoiFlagCount($themeid,0,$type,0,0),'status'=>(int)0],
            ['title'=>'待兑换','num'=>self::getKoiFlagCount($themeid,0,$type,0,1),'status'=>(int)1],
            ['title'=>'失效(已兑换其他)','num'=>self::getKoiFlagCount($themeid,0,$type,0,2),'status'=>(int)2],
            ['title'=>'当前已兑换','num'=>self::getKoiFlagCount($themeid,0,$type,0,3),'status'=>(int)3],
            ['title'=>'已核销','num'=>self::getKoiFlagCount($themeid,0,$type,0,4),'status'=>(int)4],
        ];
    }

    /**
     * Desc:获取中奖记录的实例
     * User: cbw
     * Time: 2021/1/6 9:01 上午
     * @param $themeid
     * @param $id
     * @return false
     */
    public static function getKoiFlagItemById($themeid,$id)
    {
        $res = db_get(koi_flag,['f_id'=>$id,'themeid'=>$themeid]);
        if (!$res){
            return false;
        }else{
            if ($res['from_type']=='default'){
                $sql = " select a.status,b.username,b.avatar,b.nickname,b.mobile,c.name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img,c.detail_imgs from ".tablename(koi_flag).
                    " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                    "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid and a.f_id=$id limit 1";
                return db_find($sql);
            }elseif ($res['from_type']=='koi'){
                $sql = " select a.status,b.username,b.avatar,b.nickname,b.mobile,c.title,c.img from ".tablename(koi_flag).
                    " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                    " LEFT JOIN". tablename(koi_list). " as c on a.from_type_id=c.l_id where a.themeid=$themeid and a.f_id=$id limit 1";
                return db_find($sql);
            }
        }
    }

    /**
     * Desc:判断 锦鲤记录中是否存在未使用的记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/18 8:36 下午
     * @param $themeid  //活动id
     * @param $used_koi_id  [锦鲤id]
     * @param int $status   [状态 1待兑换 2已兑换其他，当前失效 3已兑换 4 已核销]
     * @param int $used     [状态 1已使用 2未使用]
     * @param string $from_type     [中奖类型  default默认抽奖  koi锦鲤集将]
     * @return mixed
     */
    public static function getKoiFlagItemByKoiId($themeid,$used_koi_id,$uid,$used=2,$from_type='default')
    {
        return db_get(koi_flag,['themeid'=>$themeid,'uid'=>$uid,'used_koi_id'=>$used_koi_id,'used'=>$used,'from_type'=>$from_type]);
    }

    /**
     * Desc:插入中奖记录
     * User: cbw
     * Time: 2021/1/9 10:56 上午
     * @param $data
     * @return false
     */
    public static function insertKoiFlagItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_flag,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    /**
     * Desc:更新中奖记录
     * User: cbw
     * Time: 2021/1/16 9:58 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editKoiFlagItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(koi_flag,$data,$where);
        return $res;
    }

    /**
     * Desc:中奖记录核销
     * User: cbw
     * Time: 2021/1/16 10:08 下午
     * @param $f_id
     * @param $themeid
     * @return bool
     */
    public static function verificationFlag($f_id,$themeid)
    {
        $flag_item = db_get(koi_flag,['f_id'=>$f_id,'themeid'=>$themeid]);
        if ($flag_item['status']==1){
            $update_item = db_update(koi_flag,['status'=>4,'used'=>1],['f_id'=>$f_id,'themeid'=>$themeid]);
            $update_other = db_update(koi_flag,['status'=>2],['uid'=>$flag_item['uid'],'from_type'=>$flag_item['from_type'],'status'=>1,'themeid'=>$themeid]);
            if ($update_item && $update_other){
                return true;
            }
        }else{
            return false;
        }
    }

    /**
     * Desc:获取用户查询的奖品id 的中奖次数
     * User: cbw
     * Time: 2021/1/9 9:39 上午
     * @param $themeid
     * @param $uid
     * @param $p_id
     * @return mixed
     */
    public static function checkUserHasKoiFlagByPrizeId($themeid,$uid,$p_id)
    {
        $sql = " select count(*) as cnt from ".tablename(koi_flag)." where themeid=$themeid and uid='{$uid}' and from_type='default' and from_type_id=$p_id";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户的奖品
     * User: cbw
     * Time: 2021/1/15 9:45 下午
     * @param $themeid
     * @param int $uid
     * @param string $from_type
     * @param int $status
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getUserKoiFlagPrizeList($themeid,$uid=0,$from_type='default',$status=0,$page_start=0,$page_size=0)
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and a.uid='{$uid}' ";
        }
        if (!empty($from_type)){
            $condition .= " and a.from_type='".$from_type."'";
        }
        if ($status!=0){
            $condition .= " and a.status=$status";
        }
        if ($page_start && $page_size){
            $condition .= " order by a.created_at desc limit ".$page_start.",".$page_size;
        }else{
            $condition .= " order by a.created_at desc ";
        }
        if (empty($from_type)){
            $sql = "select a.status,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.name,c.name,c.short_name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img,c.detail_imgs from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid ".$condition;
            return db_select($sql);
        }elseif ($from_type=='default'){
            $sql = "select a.status,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.name,c.short_name,c.qty,c.price,c.koi_id,c.koi_title,c.small_img,c.detail_imgs from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                "  LEFT JOIN". tablename(koi_prize). " as c on c.p_id=a.from_type_id where a.themeid=$themeid ".$condition;
            return db_select($sql);
        }elseif ($from_type=='koi'){
            $sql = "select a.status,a.updated_at,a.f_id,a.from_type,a.from_type_id,b.username,b.avatar,b.nickname,b.mobile,c.title,c.img from ".tablename(koi_flag).
                " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid ".
                " LEFT JOIN". tablename(koi_list). " as c on a.from_type_id=c.l_id where a.themeid=$themeid ".$condition;
            return db_select($sql);
        }
    }

//订阅消息记录表

    /**
     * Desc:获取用户的订阅消息
     * User: cbw
     * Time: 2021/1/15 3:58 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getKoiSubMsg($themeid,$uid,$status=0)
    {
        if ($status!=0){
            $res = db_get(koi_msg,['uid'=>$uid,'themeid'=>$themeid,'status'=>$status]);
        }else{
            $res = db_get(koi_msg,['uid'=>$uid,'themeid'=>$themeid]);
        }
        return $res;
    }

    /**
     * Desc:获取订阅消息的数量
     * ser: cbw
     * Time: 2021/1/18 5:29 下午
     * @param $themeid
     * @param int $uid
     * @param int $status
     * @return mixed
     */
    public static function getKoiSubCount($themeid,$uid=0,$status=0)
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and uid='{$uid}' ";
        }
        if ($status!=0){
            $condition .= " and status=$status";
        }
        $sql = " select count(*) as cnt from ".tablename(koi_msg)." where themeid=$themeid".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取订阅消息列表s
     * User: cbw
     * Time: 2021/1/18 5:24 下午
     * @param $themeid
     * @param int $uid
     * @param int $status
     * @param int $page_start
     * @param int $page_size
     * @param string $nickname
     * @param string $mobile
     * @param string $start_day
     * @param string $end_day
     * @return mixed
     */
    public static function getKoiSubList($themeid,$uid=0,$status=0,$page_start=0,$page_size=0,$nickname='',$mobile='',$start_day='',$end_day='')
    {
        $condition = "";
        if ($uid!=0){
            $condition .= " and a.uid='{$uid}' ";
        }
        if ($status!=0){
            $condition .= " and a.status=$status";
        }
        if ($nickname){
            $condition .= "  and b.nickname like '".$nickname."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."' ";
        }
        if ($mobile){
            $condition .= "  and b.mobile='".$mobile."' ";
        }
        if ($page_start && $page_size){
            $condition .= " order by a.created_at desc limit ".$page_start.",".$page_size;
        }else{
            $condition .= " order by a.created_at desc ";
        }
        $sql = "select a.*,b.username,b.avatar,b.nickname,b.mobile,b.openid from ".tablename(koi_msg).
            " as a LEFT JOIN". tablename(t_fans). " as b on a.uid=b.uid and a.themeid=b.themeid where a.themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:更新订阅消息记录
     * User: cbw
     * Time: 2021/1/15 4:12 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editKoiSubMag($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(koi_msg,$data,$where);
        return $res;
    }

    /**
     * Desc:插入用户模版消息订阅
     * User: cbw
     * Time: 2021/1/16 5:09 下午
     * @param $data
     * @return false
     */
    public static function insertKoiSubMsg($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_msg,$data);
        if (!empty($res)){
            return $insertid;
        }else{
            return false;
        }
    }

    //数据格式化

    /**
     * Desc:格式化中奖记录
     * User: cbw
     * Time: 2021/1/7 9:54 上午
     * @param $themeid
     * @param $list
     * @return mixed
     */
    public static function formatKoiFlag($themeid,$list)
    {
        foreach ($list as $k => $val)
        {
            $type = $val['from_type'];
            $id = $val['from_type_id'];
            switch ($type){
                case 'default':

                    $lottery = self::getKoiPrizeItemById($themeid,$id);
                    $list[$k]['lottery'] = $lottery;
                    break;
                case 'koi':
                    $lottery = self::getKoiItemById($id,$themeid);
                    $list[$k]['lottery'] = $lottery;
                    break;
                default:
                    break;
            }
        }

        return $list;
    }

    /**
     * Desc:获取锦鲤已获得数据
     * User: cbw
     * Time: 2021/1/8 3:47 下午
     * @param $themeid
     * @param $uid
     * @return array[]
     */
    public static function formatGetKoiList($themeid,$uid)
    {
        $items_arr = [];
        $convert_item = self::getKoiList($themeid,'',1,0,0,1);
        foreach ($convert_item as $key =>$val){
            $item_flag_count = self::getKoiFlagCount($themeid,$uid,'koi',0,0,$val['l_id'],2);
            if ($item_flag_count){
                $temp_arr = ['name'=>$val['title'],'bak_img'=>$val['img'],'num'=>(int)$item_flag_count];
                if (count($items_arr)<5){
                    array_push($items_arr,$temp_arr);
                }
            }

        }

        $default_arr = [];
        $show_koi_items = self::getKoiList($themeid,'',2,0,0);
        foreach ($show_koi_items as $k =>$v){
            $item_flag_count = self::getKoiFlagCount($themeid,$uid,'default',0,0,$v['l_id'],2);
            $temp_arr = ['name'=>$v['title'],'bak_img'=>$v['img'],'num'=>(int)$item_flag_count];
            array_push($default_arr,$temp_arr);
        }

        $default_arr = self::arraySort($default_arr,'num',SORT_DESC);
        foreach ($default_arr as $kk => $val){
            if (count($items_arr)<5){
                array_push($items_arr,$val);
            }
        }

        $convert_arr = ['name'=>$convert_item[0]['title'],'bak_img'=>$convert_item[0]['img']];
        $list=['items'=>$items_arr,'convert'=>$convert_arr];
        return $list;
    }

    /**
     * Desc:二维数组的指定字段的排序
     * User: cbw
     * Time: 2021/1/23 1:01 下午
     * @param $array
     * @param $keys
     * @param int $sort
     * @return mixed
     */
    public static function arraySort($array,$keys,$sort=SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v){
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue,$sort,$array);
        return $array;
    }

    /**
     * Desc: 格式化锦鲤攻略
     * User: cbw
     * Time: 2021/1/8 11:08 上午
     * @param $themeid
     * @param int $page_start
     * @param int $page_size
     * @param int $status
     * @return mixed
     */
    public static function formatGetKoiMethodList($themeid,$uid,$page_start=0,$page_size=0,$status=0)
    {
        $method_list= [];
        $list = self::getKoiMethodList($themeid,0,0,0);

        foreach ($list as $k => $v){
            $temp = [];
            $items = $convert = [];
            $total = 1;
            $all_has = 2;
            $has_num = 0;
            $item_used = false;
            $get_all_info =
                self::formatKoiFiveMethodToKoiItems($v['first'],$v['second'],$v['third'],$v['four'],$v['five'],$v['compose'],$themeid,$uid,$v['m_id']);
            $first = $get_all_info['first'];
            $second = $get_all_info['second'];
            $third= $get_all_info['third'];
            $four = $get_all_info['four'];
            $five = $get_all_info['five'];
            $compose = $get_all_info['compose'];
            if ($v['first']){
                $total+=1;
                array_push($items,$first);
                if ($first['has']){
                    $has_num +=1;
                }
            }
            if ($v['second']){
                $total+=1;
                array_push($items,$second);
                if ($second['has']){
                    $has_num +=1;
                }
            }
            if ($v['third']){
                $total+=1;
                array_push($items,$third);
                if ($third['has']){
                    $has_num +=1;
                }
            }
            if ($v['four']){
                $total+=1;
                array_push($items,$four);
                if ($four['has']){
                    $has_num +=1;
                }
            }
            if ($v['five']){
                $total+=1;
                array_push($items,$five);
                if ($five['has']){
                    $has_num +=1;
                }
            }

            $convert = $compose;
            if ($compose['has']){
                $item_used = true;
            }
            if ($has_num == $total-1){
                $all_has = 1;
                $convert['name']='合成'.$convert['name'];
            }
            if ($compose['has']){
                $all_has = 3;
            }
            $temp = ['items'=>$items,'m_id'=>$v['m_id'],'convert'=>$convert,'num_total'=>$total,'used'=>$item_used,'all_has'=>$all_has];
            array_push($method_list,$temp);
        }
        $list = self::formatGetKoiList($themeid,$uid);
        $detail = '';
        $detail_btn_txt = '查看霸王锦鲤详情';
        $back_img = '';
        return ['list'=>$list,'detail'=>$detail,'back_img'=>$back_img,'method_list'=>$method_list,'detail_btn_txt'=>$detail_btn_txt];
    }


    /**
     * Desc:查询中奖记录中奖品对应的锦鲤
     * User: cbw
     * Time: 2021/1/8 3:31 下午
     * @param $themeid
     * @param $koi_id
     * @return mixed
     */
    public static function getPrizeInKoiItem($themeid,$koi_id,$uid,$used=0,$type='default',$m_id=0)
    {
        $total = 0;
        if ($type=='default'){
            $sql = "select * from ".tablename(koi_prize)." where themeid=$themeid and koi_id=$koi_id";
            $list = db_select($sql);
            if ($list){
                $ids = '';
                foreach ($list as $k => $v){
                    $ids .=$v['p_id'].',';
                }
                $ids = '('.rtrim($ids,',').')';
                $condition = " where themeid=$themeid and from_type='default' ";
                if ($used){
                    $condition.= "and used=2 ";
                }
                $condition .= "  and uid='{$uid}' and from_type_id in $ids";
                $new_sql = "select count(*) as cnt from ".tablename(koi_flag).$condition;
                $total = db_find($new_sql)['cnt'];
            }
        }else{
            $condition = " where themeid=$themeid and from_type='koi' and from_type_id=$m_id";
            if ($used){
                $condition.= "and used=2 ";
            }
            $condition .= "  and uid='{$uid}' and used_koi_id=$koi_id";
            $new_sql = "select count(*) as cnt from ".tablename(koi_flag).$condition;
            $total = db_find($new_sql)['cnt'];
        }

        return $total;
    }

    /**
     * Desc:格式化攻略中的锦鲤信息
     * User: cbw
     * Time: 2021/1/8 11:05 上午
     * @param $code
     * @param $themeid
     * @return array
     */
    public static function formatKoiMethodToKoiItem($code,$themeid,$uid,$used=2,$type='default',$m_id=0)
    {
        if ($code){
            $res = self::getKoiItemById($code,$themeid);
            $item_total = self::getPrizeInKoiItem($themeid,$res['l_id'],$uid,$used,$type,$m_id);
            return ['name'=>$res['title'],'bak_img'=>$res['img'],'has'=>$item_total>0?true:false];
        }else{
            return [];
        }
    }


    /**
     * Desc:格式化攻略中的锦鲤信息
     * User: cbw
     * Time: 2021/1/17 5:06 下午
     * @param $first_code
     * @param $sec_code
     * @param $third_code
     * @param $four_code
     * @param $five_code
     * @param $compose_code
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function formatKoiFiveMethodToKoiItems($first_code,$sec_code,$third_code,$four_code,$five_code,$compose_code,$themeid,$uid,$m_id=0)
    {
        $list = self::getKoiList($themeid,'',2);
        $all_arr = [];
        $return_arr = [];
        foreach ($list as $key => $val)
        {
            $user_has_total = self::getPrizeInKoiItem($themeid,$val['l_id'],$uid,2);
            $temp_arr = ['l_id'=>$val['l_id'],'user_has_total'=>(int)$user_has_total];
            array_push($all_arr,$temp_arr);
        }
        foreach ($all_arr as $k => &$v){
            if ($first_code){
                if ($v['l_id'] == $first_code){
                    $first_res = self::getKoiItemById($first_code,$themeid);
                    if ($v['user_has_total']>0){
                        $dd = $v['user_has_total']-1;
                        $v['user_has_total']  = $dd;
                        $first_item = ['name'=>$first_res['title'],'bak_img'=>$first_res['img'],'has'=>true];
                    }else{
                        $first_item = ['name'=>$first_res['title'],'bak_img'=>$first_res['img'],'has'=>false];
                    }
                    $return_arr['first'] = $first_item;
                }
            }else{
                $return_arr['first'] = [];
            }
            if ($sec_code){
                if ($v['l_id']==$sec_code){
                    $sec_res = self::getKoiItemById($sec_code,$themeid);
                    if ($v['user_has_total']>0){
                        $dd1 = $v['user_has_total']-1;
                        $v['user_has_total']  = $dd1;
                        $second_item = ['name'=>$sec_res['title'],'bak_img'=>$sec_res['img'],'has'=>true];
                    }else{
                        $second_item = ['name'=>$sec_res['title'],'bak_img'=>$sec_res['img'],'has'=>false];
                    }
                    $return_arr['second'] =$second_item;
                }
            }else{
                $return_arr['second'] =[];
            }
            if ($third_code){
                if ($v['l_id']==$third_code){
                    $third_res = self::getKoiItemById($third_code,$themeid);
                    if ($v['user_has_total']>0){
                        $dd2 = $v['user_has_total']-1;
                        $v['user_has_total']  = $dd2;
                        $third_item = ['name'=>$third_res['title'],'bak_img'=>$third_res['img'],'has'=>true];
                    }else{
                        $third_item = ['name'=>$third_res['title'],'bak_img'=>$third_res['img'],'has'=>false];
                    }
                    $return_arr['third'] =$third_item;
                }
            }else{
                $return_arr['third'] =[];
            }
            if ($four_code){
                if ($v['l_id']==$four_code){
                    $four_res = self::getKoiItemById($four_code,$themeid);
                    if ($v['user_has_total']>0){
                        $dd3 = $v['user_has_total']-1;
                        $v['user_has_total']  = $dd3;
                        $four_item = ['name'=>$four_res['title'],'bak_img'=>$four_res['img'],'has'=>true];
                    }else{
                        $four_item = ['name'=>$four_res['title'],'bak_img'=>$four_res['img'],'has'=>false];
                    }
                    $return_arr['four'] =$four_item;
                }
            }else{
                $return_arr['four'] =[];
            }
            if ($five_code){
                if ($v['l_id']==$five_code){
                    $five_res = self::getKoiItemById($five_code,$themeid);
                    if ($v['user_has_total']>0){
                        $dd4 = $v['user_has_total']-1;
                        $v['user_has_total']  = $dd4;
                        $five_item = ['name'=>$five_res['title'],'bak_img'=>$five_res['img'],'has'=>true];
                    }else{
                        $five_item = ['name'=>$five_res['title'],'bak_img'=>$five_res['img'],'has'=>false];
                    }
                    $return_arr['five'] =$five_item;
                }
            }else{
                $return_arr['five'] =[];
            }

        }

        $compose_res = self::formatKoiMethodToKoiItem($compose_code,$themeid,$uid,0,'koi',$m_id);
        $return_arr['compose'] = $compose_res;

        return $return_arr;
    }

    /**
     * Desc:格式化我得奖品
     * User: cbw
     * Time: 2021/1/8 4:28 下午
     * @param $themeid
     * @param $uid
     * @return array[]
     */
    public static function formatMyPrizeList($themeid,$uid,$config)
    {
        $prize_items = self::getUserKoiFlagPrizeList($themeid,$uid,'default');
        $convert_items= self::getUserKoiFlagPrizeList($themeid,$uid,'koi');
        $fans_entry = LingzeModel::getUserEntry($uid,$themeid);
        return self::formatPrizeByType($themeid,$prize_items,$convert_items,$fans_entry,$config);
    }

    /**
     * Desc:分别获取我的奖品中的抽奖类型和兑换类型的奖品
     * User: cbw
     * Time: 2021/1/8 4:29 下午
     * @param $themeid
     * @param $prize
     * @param $convert
     * @return array[]
     */
    public static function formatPrizeByType($themeid,$prize,$convert,$fans_entry,$config)
    {
        $default_package = [];
        $chest_flag = [];
        if ($fans_entry){
            //判断新宝箱的获取记录
            //            $prize_list = LingzeModel::getAllPrize($themeid);
            foreach ($prize_list as $k => $v)
            {
                $has = LingzeModel::getLtFlagItem($themeid,$fans_entry['uid'],$v['lc_id']);
                if ($has){
                    $temp = [
                        'title'=>$v['box_name'],
                        'img'=>$v['small_img'],
                        'name'=>$v['box_name'],
                        'desc'=>$v['chest_name'],
                        'time'=>substr($has['updated_at'],0,10),
                        'status'=>1
                    ];
                    array_push($chest_flag,$temp);

                }else{
                    $temp = [
                        'title'=>$v['box_name'],
                        'img'=>$v['small_img'],
                        'name'=>$v['box_name'],
                        'desc'=>$v['chest_name'],
                        'time'=>substr($fans_entry['updated_at'],0,10),
                        'status'=>0
                    ];
                    array_push($chest_flag,$temp);
                    break;
                }
            }
            array_multisort(array_column($chest_flag,'status'),SORT_ASC,$chest_flag);
            //选择项礼品
            $themyrecord = Record::getLastGroupByUid($fans_entry['uid'],$themeid);
            $select_gift = $themyrecord['address'];

            if ($select_gift && is_array($config['addressoptions'])){
                $options_key = array_search($select_gift,$config['addressoptions']);
                if (is_numeric($options_key)){
                    $select_gift_img = $config['optionsimg'][$options_key];
                    if ($select_gift_img && $select_gift){
                        $temp = [
                            'title'=>$config['lz_package_name'],
                            'img'=>$select_gift_img,
                            'name'=>$config['lz_package_name'],
                            'desc'=>$select_gift,
                            'time'=>substr($fans_entry['updated_at'],0,10),
                            'status'=>1
                        ];

                        array_push($default_package,$temp);
                    }
                }
            }
            //读取后台礼包奖品
            if (is_array($config)){
                $temp_arr = [0,1,2,3,4];
                foreach ($temp_arr as $kk => $vv){
                    if ($config['lingzeoptions'][$kk]){
                        $temp = [
                            'title'=>$config['lz_package_name'],
                            'img'=>$config['lingzeimg'][$kk],
                            'name'=>$config['lz_package_name'],
                            'desc'=>$config['lingzeoptions'][$kk],
                            'time'=>substr($fans_entry['updated_at'],0,10),
                            'status'=>1
                    ];
                        array_push($default_package,$temp);
                    }
                }
            }

        }
        $prize_list = $convert_list = [];
        if ($prize){
            foreach ($prize as $k =>$v){
                $item = self::getKoiPrizeItemById($themeid,$v['from_type_id']);
                $temp = [
                    'img'=>$item['small_img'],
                    'title'=>$item['koi_title'],
                    'name'=>'免费抽:'.$item['name'],
                    'desc'=>$item['short_name'],
                    'time'=>substr($v['updated_at'],0,10),
                    'status'=>$v['status']
                ];
                array_push($prize_list,$temp);
            }
        }
        if ($convert){
            foreach ($convert as $k =>$v){
                $item = self::getKoiItemById($v['from_type_id'],$themeid);
                $temp = [
                    'img'=>$item['img'],
                    'title'=>$item['title'],
                    'name'=>'免费抽:'.$item['name'],
                    'desc'=>'',
                    'time'=>substr($v['updated_at'],0,10),
                    'status'=>$v['status']
                ];
                array_push($convert_list,$temp);
            }
        }
        return ['prize_list'=>$prize_list,'convert_list'=>$convert_list,'default_package'=>$default_package,'chest_flag'=>$chest_flag];
    }

    //基础配置参数检查
    public static function BaseCheck($theme,$config,$system)
    {
        $msg = self::checkTheme($theme);
        if ($msg){
            return $msg;
        }else{
            $msg = self::checkLotteryMain($config);
            if ($msg){
                return $msg;
            }else{
                $msg = self::checkPrizeList($theme['id']);
                return $msg;
            }
        }
    }

    public static function checkTimeInActivity($config)
    {
        $show_lt= true;
        $now_time = time();
        if ($config['koi_time_range_begintime']>$now_time){
            $show_lt = false;
        }
        if ($now_time>$config['koi_time_range_endtime']){
            $show_lt = false;
        }
        return $show_lt;
    }

    /**
     * Desc:获取全部商家
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/6/11 6:53 下午
     * @param $themeid
     * @return mixed
     */
    public static function getShangJiaAll($themeid)
    {
        $res = db_getall(t_shangjia);
        return $res;
    }

    /**
     * Desc:活动状态检查
     * User: cbw
     * Time: 2021/1/7 3:14 下午
     * @param $system
     * @param $theme
     * @return array|string
     */
    public static function checkTheme($theme)
    {
        $msg= '';
        $now_time = time();
        if ($theme['begintime']>$now_time){
            $msg = modelShow(40064);
        }
        if ($now_time>$theme['endtime'] || $theme['status']==2){
            $msg = modelShow(40065);
        }
        if ($theme['status']==0){
            $msg = modelShow(40079);
        }
        return $msg;
    }

    /**
     * Desc:检查活动时间是否结束
     * User:cbw
     * Time: 2021/2/10 1:06 上午
     * @param $theme
     * @return bool
     */
    public static function checkThemeTime($theme)
    {
        $now_time = time();
        $msg = false;
        if ($now_time>$theme['endtime']){
            $msg = true;
        }
        return $msg;
    }

    public static function checkIskoi($config){
        global $_G;
        //判断是否开启抽奖或是否为测试用户
        $iskoi = 0;
        $config['koi_test_user'] = ",".$config['koi_test_user'].",";
        if ($config['koi_lottery_main'] ||  stripos($config['koi_test_user'],",".$_G['member']['uid'])!==false ){
            $iskoi = 1;
        }
        return $iskoi;
    }

    /**
     * Desc:检查抽奖开关
     * User: cbw
     * Time: 2021/1/7 3:21 下午
     * @param $config
     * @return array|string
     */
    public static function checkLotteryMain($config)
    {
        $msg = '';
        if (!Koi::checkIskoi($config)){
            $msg = modelShow(40080);
        }
        return $msg;
    }

    /**
     * Desc:检查奖项设置是否是4的倍数
     * User: cbw
     * Time: 2021/1/12 1:20 下午
     * @param $themeid
     * @return string
     */
    public static function checkPrizeList($themeid)
    {
        // $list_count = self::getKoiPrizeCount($themeid);
        // if ($list_count%3!=0){
        //     return '奖项数量不是3的倍数';
        // }else{
            return '';
        // }
    }

    /**
     * Desc:判断是否显示锦鲤五连抽
     * User: cbw
     * Time: 2021/1/15 3:30 下午
     * @param $config
     * @return int|mixed
     */
    public static function checkFiveLtStatus($config,$themeid,$uid)
    {
        $koi_five_lottery = $config['koi_five_lottery'];
        $now = time();
        if ($now-$config['koi_five_endtime']>0){
            $koi_five_lottery = 0;
        }
//        $has_sub_msg = self::getKoiSubMsg($themeid,$uid);
//        if ($has_sub_msg){
//            $koi_five_lottery = 0;
//        }
        return $koi_five_lottery;
    }
    //支付凭证页调取获取 show_koi_five_lucky  判断是否开启五连抽
    public static function getShowKoiFiveLucky($config,$themeid,$uid)
    {
        $res = false;
        $koi_five_lottery = $config['koi_five_lottery'];
        $start_time = $config['koi_five_begintime'];
        $end_time = $config['koi_five_endtime'];
        $now = time();
        if ($koi_five_lottery && $now>=$start_time && $now<$end_time ){
            $has_five_lt_flag = self::getKoiChanceCount($themeid,$uid,'five_lt',2);
            if ($has_five_lt_flag) {
                $result = self::checkHasFiveLtChance($themeid,$uid);
                $res = true;
            }
        }
        return $res;
    }

    /**
     * Desc:判断用户的拼团是否付款
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/15 7:45 下午
     * @param $uid
     * @param $config
     * @return bool
     */
    public static function checkHasOrder($uid,$config)
    {
        $themeid = $config['lz_game_themeid'];
        $res = Record::getLastGroupByUid($uid,$themeid);
        if (is_array($res) && $res){
            return true;
        }
        return false;
    }

    /**
     * Desc:检查未报名是否增加抽奖机会
     * User: cbw
     * Time: 2021/1/7 5:46 下午
     * @param $uid
     * @param $fans
     * @param $config
     * @param $themeid
     */
    public static function checkUserNoRegisterChance($uid,$fans,$config,$themeid,$from_uid)
    {
        $has_no_register_chance = self::getKoiChanceCount($themeid,$uid,'no_register');
        if ($config['koi_nobaoming'] && !$has_no_register_chance){
            $new_koi_counter = $config['koi_nobaoming']+$fans['koi_counter'];
            $max_limit = $config['koi_limit'];
            if ($new_koi_counter > $max_limit){
                $msg = '达到抽奖机会上限';
            }else{
                $data = [
                    'uid'=>$uid,
                    'type'=>'no_register',
                    'chance'=>$config['koi_nobaoming'],
                    'themeid'=>$themeid,
                    'from_uid'=>$from_uid,
                    'mark'=>1,
                ];
                $insert_chance_item = self::insertKoiChanceItem($data);
                $update_user_info = self::updateUserInfo($uid,['koi_counter'=>$new_koi_counter]);
            }
        }
    }

    /**
     * Desc:增加或者减少定制的抽奖机会
     * User: cbw
     * Time: 2021/1/8 9:05 上午
     * @param $op
     * @param int $chance_num
     * @param $type
     * @param $uid
     * @param $fans
     * @param $config
     * @param $themeid
     * @param $theme
     * @return array|string
     */
    public static function editUserKoiCounter($op,$chance_num=1,$type,$uid,$from_uid,$fans,$config,$themeid,$theme)
    {
        $msg = '';
        $fans = Koi::getUserInfoById($uid,$themeid);
        $koi_counter = $fans['koi_counter'];
        $check_theme_msg = self::checkTheme($theme);
        $check_lt_msg = self::checkLotteryMain($config);
        $used_flag = self::getNewKoiFlagCount($themeid,$fans['uid'],'default');
        if (!$check_theme_msg && !$check_lt_msg){
            if ($op=='add'){
                //判断用户的抽奖机会与机会上限 包含已使用的
                $new_koi_counter = $koi_counter+$used_flag+$chance_num;

                $max_limit = $config['koi_limit'];
                if ($new_koi_counter > $max_limit){
                    $msg = '达到抽奖机会上限';
                }else{
                    $data = [
                        'uid'=>$uid,
                        'type'=>$type,
                        'chance'=>$chance_num,
                        'themeid'=>$themeid,
                        'from_uid'=>$from_uid
                    ];
                    if ($type=='friend_view'){
                        $insert_chance_item = self::insertKoiChanceItem($data);
                        //判断未标记的好友到访的记录数
                        $no_mark_friend_view_chance_count = self::getKoiChanceCount($themeid,$uid,'friend_view',2);
                        if ($no_mark_friend_view_chance_count>=$config['koi_view']){
                            //标记好友到访的记录
                            $where = [
                                'uid'=>$uid,
                                'type'=>'friend_view',
                                'themeid'=>$themeid,
                                'mark'=>2
                            ];
                            $update_data = [
                                'mark'=>1
                            ];
                            $update_no_mark_friend_view_chance = self::editKoiChanceItemByWhere($where,$update_data);
                            $new_koi_counter = $koi_counter+1;
                            $update_user_info = self::updateUserInfo($uid,['koi_counter'=>$new_koi_counter]);
                        }
                        return $msg;
                    }else{
                        $insert_chance_item = self::insertKoiChanceItem($data);
                        $update_user_info = self::updateUserInfo($uid,['koi_counter'=>$new_koi_counter]);
                        return $msg;
                    }
                }
            }elseif ($op=='minus'){
                $new_koi_counter = $koi_counter-$chance_num;
                if ($new_koi_counter>=0){
                    $data = [
                        'uid'=>$uid,
                        'type'=>'system',
                        'chance'=> -$chance_num,
                        'themeid'=>$themeid,
                        'from_uid'=>0
                    ];
                    $insert_chance_item = self::insertKoiChanceItem($data);
                    $update_user_info = self::updateUserInfo($uid,['koi_counter'=>$new_koi_counter]);
                }else{
                    $msg = '抽奖机会为0';
                }
            }
        }else{
            if ($check_theme_msg){
                $msg = $check_theme_msg;
                return $msg;
            }
            if ($check_lt_msg){
                $msg = $check_lt_msg;
                return  $msg;
            }
        }
        return $msg;
    }

    //判断用户是否到达抽奖次数
    public static function checkUserUsedMaxChance($fans,$themeid,$config)
    {
        $koi_counter = $fans['koi_counter'];
        $used_flag = self::getNewKoiFlagCount($themeid,$fans['uid'],'default');

        $new_koi_counter = $koi_counter+$used_flag;
        $max_limit = $config['koi_limit'];
        if ($new_koi_counter>=$max_limit){
            return true;
        }else{
            return false;
        }
    }

    /**
     * Desc:获取抽奖信息
     * User: cbw
     * Time: 2021/1/8 10:25 上午
     * @param $uid
     * @param $from_uid
     * @param $themeid
     * @return array
     */
    public static function getGridKoiInfo($uid,$from_uid,$themeid)
    {
        $fans = self::getUserInfoById($uid,$themeid);

        $text = '开始抽奖';
        $from_type = 'default';
        $lt_chance_tips = '暂无抽奖机会';
        $lt_chance = $fans['koi_counter'];
        $flag_count = self::getKoiFlagCount($themeid,$uid);
        $config =   Theme::getConfig($themeid);
        $to_max_chance = Koi::checkUserUsedMaxChance($fans,$themeid,$config);
        if ($lt_chance>0){
            $lt_chance_tips = '您还有'.$lt_chance.'次抽奖机会';
        }else{
            $text = '再抽一次';
            if ($to_max_chance){
                $text = '兑换奖品';
            }
        }
        if ($fans['koi_is_form_worker']==1){
            $from_type = 'worker';
        }else{
            $from_type = 'default';
        }
//        if ($flag_count>0){
//            $text = '再抽一次';
//        }
        $grid_btn = ['text'=>$text,'from_type'=>$from_type];
        $grid_list = Koi::getKoiPrizeListJoinKoi($themeid,'',0,0);
        $grid_list_keys_arr = array_rand($grid_list,9);
        $new_grid_list = [];
        $p_ids='';
        foreach ($grid_list_keys_arr as $k) {
            $p_ids .= $grid_list[$k]['p_id'].',';
            unset($grid_list[$k]['pr']);
            unset($grid_list[$k]['show_sort']);
            unset($grid_list[$k]['qty']);
            unset($grid_list[$k]['status']);
            unset($grid_list[$k]['is_lose']);
            array_push($new_grid_list,$grid_list[$k]);
        }
        $p_ids = rtrim($p_ids,',');
        shuffle($new_grid_list);
        $grid_koi = [
            'lt_chance'=>(int)$lt_chance,
            'lt_chance_tips'=>$lt_chance_tips,
            'grid_btn'=>$grid_btn,
            'grid_list'=> $new_grid_list,
            'p_ids'=> $p_ids
        ];
        return $grid_koi;
    }

    /**
     * Desc:二维数组打乱排序
     * User: cbw
     * Time: 2021/1/23 1:52 下午
     * @param $list
     * @return array
     */
    public static function shuffle_assoc($list)
    {
        if (!is_array($list)) return $list;
        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $list[$key];
        return $random;
    }

    /**
     * Desc:判断是否由他人转发链接进入  给转发人增加抽奖机会
     * User: cbw
     * Time: 2021/1/9 2:25 下午
     * @param $themeid
     * @param $fromuid
     * @param $uid
     */
    public static function checkFromUserAddChance($themeid,$fromuid,$uid,$is_new_user,$config,$theme)
    {
        if ($fromuid!=0 && $fromuid!=$uid){
            $has_friend_view_count = self::getKoiChanceCount($themeid,$fromuid,'friend_view',0,$uid);
            if ($config['koi_view']>0 && $is_new_user && !$has_friend_view_count){
                //给上一级增加机会
                $d_chance = 1/$config['koi_view'];
                $chance = number_format($d_chance,1);
                $from_fans = self::getUserInfoById($fromuid,$themeid);
                $add_chance_res = self::editUserKoiCounter('add',$chance,'friend_view',$fromuid,$uid,$from_fans,$config,$themeid,$theme);
            }
        }

        $fans = self::getUserInfoById($uid,$themeid);
        //给自己增加
        $has_lucky_star_chance = self::getKoiChanceCount($themeid,$uid,'lucky_star');
        if ($has_lucky_star_chance<1 && $is_new_user && $config['koi_nobaoming']){

            $new_koi_counter = $config['koi_nobaoming']+$fans['koi_counter'];
            $max_limit = $config['koi_limit'];
            if ($new_koi_counter > $max_limit){
                $msg = '达到抽奖机会上限';
            }else{
                $self_data = [
                    'uid'=>$uid,
                    'type'=>'lucky_star',
                    'chance'=>$config['koi_nobaoming'],
                    'mark'=>2,
                    'themeid'=>$themeid,
                    'from_uid'=>$fromuid
                ];
                $add_chance_res = self::editUserKoiCounter('add',$config['koi_nobaoming'],'lucky_star',$uid,$fromuid,$fans,$config,$themeid,$theme);
            }
        }
    }

    /**
     * Desc:查询定时记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/5/6 1:17 上午
     * @param $where
     * @return mixed
     */
    public static function getTimeSetFlagItem($where)
    {
        return db_get(koi_timeset,$where);
    }

    //插入定时记录
    public static function insertTimeSetItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(koi_timeset,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }
    //修改定时记录
    public static function editTimeSetItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(koi_timeset,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }

    public static function getNoReceiveTypeFlag($uid,$themeid,$type=0)
    {
        if (empty($uid)){
            return ;
        }
        $condition = " WHERE uid='{$uid}' AND themeid=$themeid  AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
        if ($type){
            $condition = " WHERE uid='{$uid}' AND themeid=$themeid AND status=$type AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
        }

        $sql = " SELECT * FROM ".tablename(koi_timeset).$condition;
        return db_find($sql);
    }

    //获取最后一条待领取的计时机会
    public static function getLastWaitFlag($uid,$themeid,$status=1)
    {
        if (empty($uid)){
            return ;
        }
        if ($status) {
            $condotion = " WHERE uid='{$uid}' AND themeid=$themeid AND status=$status AND TO_DAYS(created_at) <= TO_DAYS(NOW()) ORDER BY created_at DESC";
        } else {
            $condotion = " WHERE uid='{$uid}' AND themeid=$themeid AND TO_DAYS(created_at) <= TO_DAYS(NOW())  ORDER BY created_at DESC";
        }
        $sql = " SELECT * FROM ".tablename(koi_timeset).$condotion;
        return db_find($sql);
    }

    /**
     * Desc:获取用户的帮助进度文字
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/16 4:45 下午
     * @param $themeid
     * @param $uid
     * @param $config
     * @return string
     */
    public static function getUserFriendViewProcess($themeid,$uid,$config)
    {
        $msg = 0;
        $fans = self::getUserInfoById($uid,$themeid);
        $new_koi_counter = $config['koi_nobaoming']+$fans['koi_counter'];
        $max_limit = $config['koi_limit'];
        if ($new_koi_counter > $max_limit) {
//            $msg = '达到抽奖机会上限';
        }else{
            $one_total = $config['koi_view'];
            //判断未标记的好友到访数量
            $no_mark_total = (int)self::getKoiChanceCount($themeid,$uid,'friend_view',2);
            $remain = intval($one_total-$no_mark_total);
            if ($remain>0){
                $msg = $remain;
//                $msg = '继续邀请'.$remain.'位好友到访，可增加一次抽奖机会';
            }else{
                $msg = $one_total;
//                $msg = '邀请'.$one_total.'位好友到访增加一次抽奖机会';
            }
        }
        return $msg;
    }

    /**
     * Desc:检查用户是否订阅五连抽消息 并在指定时间范围内进入
     * User: cbw
     * Time: 2021/1/15 4:22 下午
     * @param $themeid
     * @param $uid
     * @param $config
     */
    public static function checkInFiveLtTime($themeid,$uid,$config)
    {
        $koi_five_lottery = $config['koi_five_lottery'];
        $start_time = $config['koi_five_begintime'];
        $end_time = $config['koi_five_endtime'];
        $now = time();
        $has_five_lt_flag = self::getKoiChanceCount($themeid,$uid,'five_lt');
        if ($koi_five_lottery && $now>=$start_time && $now<$end_time && !$has_five_lt_flag){
            //插入五连抽
            $insert_data = [
                'uid'=>$uid,
                'type'=>'five_lt',
                'chance'=>5,
                'mark'=>2,
                'themeid'=>$themeid
            ];
            $insert_five_lt_chance = self::insertKoiChanceItem($insert_data);
        }
    }

    /**
     * Desc:获取用户是否是幸运星
     * User: cbw
     * Time: 2021/1/9 3:00 下午
     * @param $themeid
     * @param $uid
     * @param $config
     * @return array
     */
    public static function checkUserHasLuckyStarChance($themeid,$uid,$config,$from_uid)
    {
        $lucky_star = ['has'=>false,'info'=>[]];
        $has_lucky_star_chance = self::getUserluckyStarChanceItem($themeid,$uid,$from_uid);

        if ($has_lucky_star_chance){

            if (!$has_lucky_star_chance['from_uid']){
                $theme = Theme::getThemeById($themeid);
                $from_user_info = ['avatar'=>$config['pinpailogo'],'username'=>$theme['jubf'],'nickname'=>$theme['jubf']];
            }else{
                $from_user_info = self::getUserInfoById($has_lucky_star_chance['from_uid'],$themeid);
            }
            $lucky_star['has'] = true;
            $lucky_star['info'] = [
                'title'=>'幸运星',
                'name'=>'恭喜获得幸运星1枚',
                'desc'=>$config['koi_lucky_star'],
                'add_chance'=>$config['koi_nobaoming'],
                'btn_txt'=>'快去抽奖',
                'from_user_avatar'=>$from_user_info['avatar'],
                'from_user_name'=>$from_user_info['username'],
                'from_user_nick'=>$from_user_info['nickname']
            ];
            //更新幸运星为标记
            $where = [
                'c_id'=>$has_lucky_star_chance['c_id']
            ];
            $update_data = ['mark'=>1];
            $update = self::editKoiChanceItemByWhere($where,$update_data);
        }
        return $lucky_star;
    }

    /**
     * Desc:判断用户是否有获得五连抽的机会
     * User: cbw
     * Time: 2021/1/15 3:38 下午
     * @param $themeid
     * @param $uid
     * @return int
     */
    public static function checkHasFiveLtChance($themeid,$uid)
    {
        $where = [
            'uid'=>$uid,
            'themeid'=>$themeid,
            'type'=>'five_lt',
            'mark'=>2
        ];
        $res = self::getKoiChanceItemByWhere($where);
        if (!$res){
            return 0;
        }else{
            $new_where = ['c_id'=>$res['c_id']];
            $data = ['mark'=>1];
            $update = self::editKoiChanceItemByWhere($new_where,$data);
            $new_koi_counter = self::getUserInfoById($uid,$themeid)['koi_counter']+5;
            $update_user_info = self::updateUserInfo($uid,['koi_counter'=>$new_koi_counter]);
            return 1;
        }
    }

    /**
     * Desc:判断来自好友还是工作人员
     * User: cbw
     * Time: 2021/1/8 9:41 上午
     * @param $from_uid
     * @param $themeid
     * @return string
     */
    public static function checkFromType($from_uid,$themeid)
    {
        $type = 'friend';
        $isworker = Worker::getThemeWorkerByUid($from_uid,$themeid,1);
        if (!empty($isworker)){
            $type = 'worker';
        }
        return $type;
    }

    /**
     * Desc:判断来自好友还是工作人员
     * User: cbw
     * Time: 2021/1/8 9:41 上午
     * @param $from_uid
     * @param $themeid
     * @return string
     */
    public static function checkFromTypeNew($fans,$from_uid,$themeid)
    {
        if ($fans['koi_is_form_worker']==0){
            if (empty($from_uid)){
                $from_uid = $fans['uid'];
            }

            $isworker = Worker::getThemeWorkerByUid($from_uid,$themeid,1);
            if (!empty($isworker)){
                db_query("UPDATE ".tablename(t_fans)." SET koi_is_form_worker = 1 WHERE  id ={$fans['id']}");
                $fans['koi_is_form_worker']=1;
            }
        }
        return $fans;
    }

    public static function getUserInfoById($uid,$themeid)
    {
        $res = db_get(t_fans,['uid'=>$uid,'themeid'=>$themeid]);
        return $res;
    }

    public static function updateUserInfo($uid,$data)
    {
        $res = db_update(t_fans,$data,['uid'=>$uid]);
    }

    /**
     * Desc:判断是否是新用户
     * User: cbw
     * Time: 2021/1/9 2:55 下午
     * @param $fans
     * @return bool
     */
    public static function checkNewUser($fans)
    {
        $is_new_user = false;
        if (!$fans['username'] || !$fans['mobile']){
            $is_new_user = true;
        }
        return $is_new_user;
    }

    /**
     * Desc:获取授权信息
     * User: cbw
     * Time: 2021/1/16 2:50 下午
     * @param $config
     * @param $uid
     * @return array
     */
    public static function getNeedInfo($config,$uid,$themeid)
    {
        $koi_userinfo = $config['getavatar'];
        $koi_mobile = $config['getmobile'];
        $koi_register = $config['koi_register'];
        $fans = self::getUserInfoById($uid,$themeid);
        if ($koi_mobile!=1){
            $koi_mobile = 0;
        }elseif ($koi_mobile==1 && $fans['mobile']){
            $koi_mobile = 0;
        }
        if ($koi_userinfo!=1){
            $koi_userinfo = 0;
        }
        if ($config['koi_register']==1 && $fans['username'] && $fans['mobile']){
            $koi_register = 0;
        }
        $need_info = [
            'koi_userinfo'=>$koi_userinfo,
            'koi_mobile'=>$koi_mobile,
            'koi_register'=>$koi_register
        ];
        return $need_info;
    }

    /**
     * Desc:发送订阅消息
     * User: cbw
     * Time: 2021/1/16 4:58 下午
     * @param $uid
     * @param $system
     * @param $template_id
     * @param $page
     */
    public static function sendWxMsg($uid,$system,$page,$themeid,$msg='')
    {
        //调用订阅消息
        $fans = self::getUserInfoById($uid,$themeid);
        $openid = $fans['openid'];
        $username = $fans['username']?$fans['username']:$fans['nickname'];
        $appid = $system['appid'];
        $appsecret = $system['secret'];
        $template_id = 'xhtqfQ0a7GHKYBLydc7fMC4vlsu9cLzd6oWWij6vnG0';
        $page = $page['page'];
        if (!$msg){
            $msg = '锦鲤五连抽活动开始，点击进入获取抽奖机会';
        }
        $res_data = [
            'thing1'=>$username,//预约人
            'thing6'=>'共享宝箱提醒',//活动名称
            'thing7'=>$msg,//活动内容
        ];
        $postData = [
            'appid'=>$appid,
            'appsecret'=>$appsecret,
            'touser'=>$openid,
            'template_id'=>$template_id,
            'page'=>'/bargain/pages/bargain/bargain/',
            'res_data'=>$res_data
        ];
        try {
            self::sendMessage($system,$postData);
            return true;
        }catch (Exception $e){
            return false;
        }

    }
    static function sendMessage($system,$postData)
    {

        $touser = $postData['touser'];
        $template_id = $postData['template_id'];
        $page = $postData['page'];

//        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret=' . $appsecret;
//        $res = json_decode(file_get_contents($url),true);
//        $access_token = $res['access_token'];


        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=';
        //发送内容
        $data = [] ;
        //接收者（用户）的 openid
        $data['touser'] = $touser;
        //所需下发的订阅模版id
        $data['template_id'] = $template_id;
        //点击模版卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模版无跳转。
        $data['page'] = $page;
        $data['data'] = $postData['res_data'];


        //跳转小程序类型：developer 为开发版；trial 为体验版；formal 为正式版；默认为正式版
        $data['miniprogram_state'] = 'developer';

        $res = PostByAccessToken($system,$url,$data);
        return json_decode($res,true);

    }
    /**
     * Desc:获取特殊协议链接地址
     * User: cbw
     * Time: 2021/1/20 2:26 下午
     * @param $system
     */
    public static function getUrlScheme($system)
    {
        $time = strtotime("+6 days");
        $appid = $system['appid'];
        $appsecret = $system['secret'];
        $jump_wxa = [
            'path'=>'/pages/index/index',
            'query'=>'softname=eu61012&themeid=1&softkey=B4Pf5aNZX'
        ];
        $postData = [
            'appid'=>$appid,
            'appsecret'=>$appsecret,
            'jump_wxa'=>$jump_wxa,
            'is_expire'=>true,
            'expire_time'=>$time,
        ];
        try {
            $res = self::getUrlScheme2($system,$postData);
            var_dump($res);die();
        }catch (Exception $e){
            var_dump($e->getMessage());die();
        }
        return $res;
    }

    public static function getUrlScheme2($system,$postData)
    {
        //请求url
        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=';

        //发送内容
        $data = [] ;
        $data['jump_wxa']=$postData['jump_wxa'];
        $data['is_expire']=$postData['is_expire'];
        $data['expire_time']=$postData['expire_time'];

        $res = PostByAccessToken($system,$url,$data);
        return json_decode($res,true);
    }
}